import { defineStore } from 'pinia'
import type { IUserInfo } from '@/types'
import { computed,ref } from 'vue'
import { useLocalStorage } from '@/use/useLocalStorage'

// 定义用户状态
export interface IUserState {
    userInfo:IUserInfo
    token:string
}

// 默认用户信息
const getDefaultUserInfo:() => IUserInfo = () => ({
    id: '',
    avatar: 'https://b.yzcdn.cn/vant/icon-demo-1126.png',
    nickname: '请登录',
})

// 定义用户状态
export const useUserStore = defineStore('user',()=> {
    const {
        value: $userInfo,
        setValue: $setUserInfoValue,
        removeItem: $removeUserInfoItem,
      } = useLocalStorage('userInfo', getDefaultUserInfo())
      const { setValue: $setTokenValue, removeItem: $removeTokenItem } = useLocalStorage('token', '')

      // 定义用户状态
      const state = ref({
        userInfo: getDefaultUserInfo(),
        token: '',
      })
     
      // 获取用户信息
    const getUserInfo = computed(() => {
        if (!state.value.userInfo || !state.value.userInfo.id) {
            state.value.userInfo = $userInfo.value
          }
          return state.value.userInfo
    });

    // 设置用户信息
    const setInfo = ({ token, userInfo }: IUserState) => {
        state.value.userInfo = userInfo
        state.value.token = token
        $setUserInfoValue(userInfo)
        $setTokenValue(token)
      }
      const removeInfo = () => {
        state.value.userInfo = getDefaultUserInfo()
        state.value.token = ''
        $removeUserInfoItem()
        $removeTokenItem()
      }


    return {
        getUserInfo,
        setInfo,
        removeInfo,
        state,
    }



  

})







